﻿using System.Data.Common;
using System.Data.SqlClient;
using System.Linq;
using Microsoft.Practices.EnterpriseLibrary.Data;
using ModulesToolkit.DataContracts;
using ModulesToolkit.DataContracts.Membership;

namespace ModulesToolkit.DataAccess.Membership
{
    /// <summary>
    /// Create Read operations for read only entities from the database
    /// </summary>
    /// <author>
    /// Mina
    /// </author>
    public class GroupsDtoRepository
    {
        #region Methods

        /// <summary>
        /// Retrieves the groups.
        /// </summary>
        /// <param name="searchCriteria">The search criteria.</param>
        /// <returns></returns>
        public EntitySearchResult<GroupDto> RetrieveGroups(GroupDtoSearchCriteria searchCriteria)
        {
            Database database = DatabaseFactory.CreateDatabase();
            using (DbCommand command = database.GetStoredProcCommand("[Membership].[RetrieveGroups]"))
            {
                try
                {
                    return new EntitySearchResult<GroupDto>(
                        database.Execute<GroupDto>(command, searchCriteria.AsParameters().ToArray()).ToList(),
                        database.GetParameterValue(command, "RETURN_VALUE").ConvertTo<int>().GetValueOrDefault()
                        );
                }
                catch (SqlException exception)
                {
                    throw exception.Translate();
                }
            }
        }

        /// <summary>
        /// Deletes the group.
        /// </summary>
        /// <param name="groupId">The group id.</param>
        public void DeleteGroup(int groupId)
        {
            Database database = DatabaseFactory.CreateDatabase();
            database.ExecuteNonQuery("[Membership].[DeleteGroup]", groupId);
        }

        /// <summary>
        /// Inserts the group.
        /// </summary>
        /// <param name="groupDto">The group dto.</param>
        public void InsertGroup(GroupDtoInsertIdentity groupDto)
        {
            Database database = DatabaseFactory.CreateDatabase();
            database.ExecuteNonQuery("[Membership].[InsertGroup]", groupDto.AsParameters());
        }

        #endregion Methods

        public void UpdateGroup(GroupDto groupDto)
        {
            Database database = DatabaseFactory.CreateDatabase();
            database.ExecuteNonQuery("[Membership].[DeleteGroup]",
                                     groupDto.AsParameters());
        }
    }
}